//
//  MovieManger.m
//  FiveWork
//
//  Created by lanou3g on 15/11/23.
//  Copyright © 2015年 Project. All rights reserved.
//

#import "MovieManger.h"
#define MovieURL @"http://api.budejie.com/api/api_open.php?a=list&appname=baisibudejie&asid=7BD90612-6C22-4D70-8B6B-D63F46B70CC8&c=video&client=iphone&device=iPhone%205&from=ios&jbk=0&mac=02%3A00%3A00%3A00%3A00%3A00&market=&maxtime=1448252762&openudid=bff483252ba2c4b59776d90fb1835b05c86fb76c&page=2&per=20&type=41&udid=&ver=3.0"
//http://api.budejie.com/api/api_open.php?a=list&appname=baisibudejie&asid=7BD90612-6C22-4D70-8B6B-D63F46B70CC8&c=video&client=iphone&device=iPhone%205&from=ios&jbk=0&mac=02%3A00%3A00%3A00%3A00%3A00&market=&openudid=bff483252ba2c4b59776d90fb1835b05c86fb76c&page=0&per=20&type=41&udid=&ver=3.0


// 内涵段子http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3228236840&idfa=idfa&version_code=4.4.2&device_type=iPhone%205%20(Global)&aid=7&os_version=9.1&screen_width=640&vid=1F75FDFB-2966-40CE-A8E3-67A11CF1BCE7&device_id=7474605904&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=b79e9208965bf4a1b8349d3304ca81ad168d22f6&channel=App%20Store&content_type=-104&count=30&essence=1&message_cursor=0&min_time=1448421754&mpic=1


//http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104&iid=3228236840&idfa=idfa&version_code=4.4.2&device_type=iPhone%205%20(Global)&aid=7&os_version=9.1&screen_width=640&vid=1F75FDFB-2966-40CE-A8E3-67A11CF1BCE7&device_id=7474605904&os_api=18&app_name=joke_essay&device_platform=iphone&ac=WIFI&openudid=b79e9208965bf4a1b8349d3304ca81ad168d22f6&channel=App%20Store&content_type=-104&count=30&essence=1&message_cursor=0&min_time=1448421895&mpic=1
#import <AFHTTPRequestOperationManager.h>
#import "MovieModel.h"
@import AVFoundation;

@interface MovieManger ()
@property(nonatomic,strong)NSMutableArray *movieArray;
@property(nonatomic,strong)AVPlayerItem *avplayerItem;
@property(nonatomic,assign)NSInteger AVIndex;
@end

@implementation MovieManger

static MovieManger *movieManger =nil;
+(instancetype)defaultMovieManager{
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        movieManger =[[MovieManger alloc] init];
    });
    return movieManger;
    
    
}

/**
 *  重写初始化方法
 */
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.AVIndex =0;
        self.UPorDown =YES;
    }
    return self;
}

/**
 *  懒加载
 */
-(NSMutableArray *)movieArray{
    if (_movieArray ==nil) {
        _movieArray =[NSMutableArray array];
        
    }
    return _movieArray;
}

-(void)prepareMoviepageWithHandle:(void (^)())handle{
    
//    NSURL *url =[NSURL URLWithString:MovieURL];
    AFHTTPRequestOperationManager *manger =[AFHTTPRequestOperationManager manager];
    manger.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"application/json"];
    
    [manger GET:MovieURL parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *sourceDict =[NSDictionary dictionaryWithDictionary:responseObject];
        NSArray *arr =sourceDict[@"list"];
        for (NSDictionary *dic in arr) {
            MovieModel  *model =[[MovieModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.movieArray addObject:model];
        }
        
//        handle();
        dispatch_async(dispatch_get_main_queue(), ^{
            handle();
        });
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"解析失败");
    }];
    
    
    
    
    
}


/**
 *  加载播放器
 */
-(void)setupAVPlayerWithModel:(MovieModel *)movie{
    
    NSURL *url =[NSURL URLWithString:movie.videouri];
    self.avplayerItem =[AVPlayerItem playerItemWithURL:url];
    self.avPlayer =[AVPlayer playerWithPlayerItem:self.avplayerItem];
    self.avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    
    
//    self.avplayerItem =[AVPlayerItem playerItemWithURL:[NSURL URLWithString:movie.videouri]];
//    self.avPlayer =[AVPlayer playerWithPlayerItem:self.avplayerItem];
//    self.avPlayerLayer =[AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
//    self.avPlayerLayer.videoGravity =AVLayerVideoGravityResizeAspect;
}

/**
 观察者方法
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    if ([keyPath isEqualToString:@"status"]) {
        if ([playerItem status] == AVPlayerStatusReadyToPlay) {
            NSLog(@"AVPlayerStatusReadyToPlay");
            
            //    self.stateButton.enabled = YES;
            //    CMTime duration = self.avplayerItem.duration;// 获取视频总长度
            //     CGFloat totalSecond = playerItem.duration.value / playerItem.duration.timescale;// 转换成秒
            //   _totalTime = [self convertTime:totalSecond];// 转换成播放时间
            //    [self customVideoSlider:duration];// 自定义UISlider外观
            //   NSLog(@"movie total duration:%f",CMTimeGetSeconds(duration));
            //    [self monitoringPlayback:self.avplayerItem];// 监听播放状态
        } else if ([playerItem status] == AVPlayerStatusFailed) {
            NSLog(@"AVPlayerStatusFailed");
        }
        //   } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        //    NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
        //    NSLog(@"Time Interval:%f",timeInterval);
        //   CMTime duration = self.playerItem.duration;
        //   CGFloat totalDuration = CMTimeGetSeconds(duration);
        //    [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
        //    }
    }
    
}


/**
 *  开始播放
 */
-(void)playerPlay{
    [self.avPlayer play];
}
/**
 *  暂停播放
 */
-(void)playerPause{
    [self.avPlayer pause];
}

/**
 *  返回model数组
 */
-(NSArray *)returnModelArray{
    return self.movieArray;
}


/**
 *  返回数组个数
 */
-(NSInteger)returnModelArrayCount{
    return self.movieArray.count;
}
/**
 *  返回model
 */
-(MovieModel*)returnMovieModelWithIndex:(NSInteger)index{
    return self.movieArray[index];
}
/**
 *  释放AVPlayer
 */
-(void)shiFang{
    [self.avPlayerLayer removeFromSuperlayer];
    self.avPlayerLayer = nil;
    self.avPlayer = nil;
    self.avplayerItem = nil;
    

}



@end
